package org.itboys.weixin;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.itboys.admin.entity.SysDictionary;
import org.itboys.admin.service.SysDictionaryService;
import org.itboys.framework.spring.context.SpringContextHolder;
import org.itboys.solr.client.SolrClient;
import org.itboys.store.cache.ProductDetailLoader;
import org.itboys.store.constant.ProductConstant;
import org.itboys.store.dto.ProductDetail;
import org.itboys.store.entity.Order;
import org.itboys.store.entity.Product;
import org.itboys.store.entity.ProductCount;
import org.itboys.store.entity.ProductStorage;
import org.itboys.store.search.ProductSearchDoc;
import org.itboys.store.search.ProductSearchService;
import org.itboys.store.service.StoreOrderService;
import org.itboys.store.service.StoreProductCountService;
import org.itboys.store.service.StoreProductService;
import org.itboys.store.service.StoreProductStorageService;
import org.itboys.store.tools.CloudBuilderInteface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Created by huml on 2016/5/11.
 * 定时任务
 * 自动发放收益
 */
@Configuration
@EnableScheduling // 启用定时任务
public class StoreSchedulingConfig {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Scheduled(cron = "0 0 0/2 * * ?") // 每天凌晨12(23:59:59)点执行一次
    public void scheduler() {
        try {
            StoreProductService storeProductService = SpringContextHolder.getBean("storeProductService");
            StoreProductStorageService storeProductStorageService = SpringContextHolder.getBean("storeProductStorageService");
            StoreProductCountService storeProductCountService = SpringContextHolder.getBean("storeProductCountService");
            SysDictionaryService sysDictionaryService = SpringContextHolder.getBean("sysDictionaryService");
            SolrClient productSolrClient = SpringContextHolder.getBean("storeProductSolrClient");
            ProductSearchService productSearchService = SpringContextHolder.getBean("storeProductSearchService");
            ProductDetailLoader productDetailLoader = SpringContextHolder.getBean("storeProductDetailLoader");
            SysDictionary sysDictionary = sysDictionaryService.getByField("key", ProductConstant.PRICE_SCALE_KEY);
            BigDecimal scale = BigDecimal.ZERO;
            if(sysDictionary != null){
                scale = new BigDecimal(sysDictionary.getValue()).divide(new BigDecimal(100));
            }
            Integer queryType = CloudBuilderInteface.QUERY_TYPE_DETAIL;
            Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
            param.put("type", Product.TYPE_HT);
            List<Product> list = storeProductService.list(param);
            if(list == null || list.isEmpty()){
                queryType = CloudBuilderInteface.QUERY_TYPE_DETAIL;
            } else {
                queryType = CloudBuilderInteface.QUERY_TYPE_SIMPLE;
            }
            logger.info("******************queryType************************" + queryType);
            list = CloudBuilderInteface.queryAllGoodsId(queryType);

            for (Product product : list) {
                product.setRealPrice(new BigDecimal(product.getPrice()).multiply(BigDecimal.ONE .add(scale)).doubleValue());
                product.setMarketPrice(product.getRealPrice() + 100);
                product.setType(Product.TYPE_HT);
            }
            if(queryType.equals(CloudBuilderInteface.QUERY_TYPE_DETAIL)){
                storeProductService.batchSave(list);
                List<ProductStorage> storages = storeProductStorageService.list(Maps.newHashMapWithExpectedSize(1));
                List<ProductStorage> storages1 = Lists.newArrayList();
                List<ProductCount> counts = Lists.newArrayListWithExpectedSize(list.size());
                for (Product product : list) {
                    ProductCount count = new ProductCount();
                    count.setProductId(product.getId());
                    counts.add(count);
                    ProductStorage storage = new ProductStorage();
                    storage.setName(product.getStorage());
                    if(!storages.contains(storage) && !storages1.contains(storage)){
                        storages1.add(storage);
                    }
                }
                if (counts != null && !counts.isEmpty()) {
                    storeProductCountService.batchSave(counts);
                }
                if(storages1 != null && !storages1.isEmpty()){
                    storeProductStorageService.batchSave(storages1);
                }
            } else {
                storeProductService.batchUpdateNoId(list);
            }
            //solr
            for (Product product : list) {
                productSolrClient.deleteDocument(product.getId() + "");
                ProductDetail detail = productDetailLoader.get(product.getId());
                ProductSearchDoc doc = new ProductSearchDoc();
                doc.setProductId(product.getId());
//                doc.setBrandId(detail.getBrandId());
//                doc.setCategoryFullIdPath(detail.getCatId().toString());
                doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
                doc.setPrice(detail.getRealPrice());
                doc.setSoldCount(detail.getSoldCount());
                doc.setReadCount(detail.getReadCount());
                doc.setType(Product.TYPE_HT);
                productSearchService.buildProductSearchIndex(doc);
            }
            logger.info("******************产品信息同步成功************************");
        } catch (Exception e) {
            logger.info("******************产品信息同步失败************************", e);
        }
    }
    @Scheduled(cron = "0 0/5 * * * ?") // 每天凌晨12(23:59:59)点执行一次
    public void queryOrder(){
        StoreOrderService storeOrderService = SpringContextHolder.getBean("storeOrderService");
        // 查询出所有未完成的订单
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
        param.put("isDeleted", 0);
        param.put("status !=", ProductConstant.OrderStatic.ORDER_STATUS_SUCCESS);
        List<Order> orders = storeOrderService.list(param);
        if(orders != null && !orders.isEmpty()){
            List<Order> orders1 = Lists.newArrayList();
            for (Order order : orders) {
                try {
                    JSONObject object = CloudBuilderInteface.queryOrderInfo(order.getOrderNo());
                    Integer recCode = (Integer)object.get("recCode");
                    if(recCode.equals(HttpStatus.OK)){
                        JSONArray array = object.getJSONArray("result");
                        JSONObject orderObject = (JSONObject) array.get(0);
                        Integer status = (Integer) orderObject.get("status");
                        if(status.equals(CloudBuilderInteface.QUERY_ORDER_STATUS_SEND_SUCCESS)){//已发货
                            order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_SEND);
                            order.setExpress((String)orderObject.get("deliverName"));
                            order.setExpressNo((String)orderObject.get("deliverNo"));
                            orders1.add(order);
                        }
                    }
                } catch (Exception e) {
                    logger.info("******************订单"+order.getOrderNo()+"同步失败************************", e);
                    continue;
                }
            }
            logger.info("****************order size*****************" + orders1.size());
            if(orders1 != null && !orders1.isEmpty()){
                storeOrderService.batchUpdate(orders1);
            }
        }
        logger.info("******************订单同步成功************************");
    }


}
